package com.feilong.edgeAI.update;

import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.ToastUtils;
import com.feilong.edgeAI.BuildConfig;
import com.feilong.edgeAI.R;
import com.feilong.edgeAI.model.DownloadProgress;
import com.feilong.edgeAI.model.PlayTTs;
import com.feilong.edgeAI.model.RequestInstallApk;
import com.feilong.edgeAI.model.ShowDownLoadDialog;
import com.feilong.edgeAI.model.StartInstallApk;
import com.feilong.edgeAI.model.TcpUpdateFeiLong;
import com.feilong.edgeAI.utils.AppUtils;
import com.feilong.edgeAI.utils.FileUtil;
import com.feilong.edgeAI.utils.NotificationUtils;
import com.xuexiang.xui.widget.dialog.materialdialog.GravityEnum;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.progress.HorizontalProgressView;
import com.xuexiang.xutil.file.FileUtils;
import com.xuexiang.xutil.file.ZipUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

public class XxzUpdateService extends IntentService {
    private static final int BUFFER_SIZE = 10 * 1024; // 8k ~ 32K
    private static final String TAG = "ApkUpdateService";
    private String channelId = "update";
    private NotificationManager mNotifyManager;
    private
    NotificationCompat.Builder mBuilder;
    public static final String XXZ_DOWNLOAD_URL = "url";

    public XxzUpdateService() {
        super("ApkUpdateService");
    }

    private static final String CHANNEL_ID = "ApkUpdateService";
    private static final int NOTIFICATION_ID = 102;
    private File downloadFile;

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startForeground() {
        // Create Notification Channel
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "feilong",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }

        // Create Notification
        Notification notification = new Notification.Builder(this, CHANNEL_ID)
                .setContentTitle("飞龙芯更新")
                .setContentText("Service is running...")
                .build();

        // Start Foreground Service with notification
        startForeground(NOTIFICATION_ID, notification);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onHandleIntent(Intent intent) {
        startForeground();
        String urlStr = intent.getStringExtra(XXZ_DOWNLOAD_URL);
        Log.d(TAG, "onHandleIntent: " + urlStr);
        InputStream in = null;
        FileOutputStream out = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(false);
            urlConnection.setConnectTimeout(10 * 1000);
            urlConnection.setReadTimeout(10 * 1000);
//			urlConnection.setRequestProperty("Connection", "Keep-Alive");
//			urlConnection.setRequestProperty("Charset", "UTF-8");
//			urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");

            urlConnection.connect();
            long bytetotal = urlConnection.getContentLength();
            long bytesum = 0;
            int byteread = 0;
            in = urlConnection.getInputStream();
            File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
            String apkName = "exagear.zip";
            downloadFile = new File(dir, apkName);
            if (downloadFile.exists()) {
                downloadFile.delete();
            }
            downloadFile.createNewFile();
            Log.d(TAG, "onHandleIntent: downloadFile=" + downloadFile.getAbsolutePath() + "  length=" + downloadFile.length());
            out = new FileOutputStream(downloadFile);
            byte[] buffer = new byte[BUFFER_SIZE];
            EventBus.getDefault().post(new ShowDownLoadDialog(true, getString(R.string.content_downloading)));
            int oldProgress = 0;
            while ((byteread = in.read(buffer)) != -1) {
                bytesum += byteread;
                out.write(buffer, 0, byteread);

                int progress = (int) (bytesum * 100L / bytetotal);
                // 如果进度与之前进度相等，则不更新，如果更新太频繁，否则会造成界面卡顿
                if (progress != oldProgress) {
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                        updateProgress(progress);
                    } else {
                        EventBus.getDefault().post(new DownloadProgress(progress));
                        String downProgress = this.getString(R.string.download_progress, progress);
                        NotificationUtils.showNotification("飞龙码离线引擎更新", downProgress, 0, channelId, progress, 100);
                    }
                }
                oldProgress = progress;
            }
            EventBus.getDefault().post(new ShowDownLoadDialog(true, "理解引擎更新已完成，请重启手机使之生效"));
//            EventBus.getDefault().post(new ShowDownLoadDialog(true, getString(R.string.init_xxz)));
            out.flush();
//            out.close();
//            Log.d(TAG, "onHandleIntent: downloadFile>>>="+downloadFile.getAbsolutePath()+"  length="+downloadFile.length());
            File zipFile = null;
            File[] filess = dir.listFiles();
            for (File file : filess) {
                if (file.getName().equals(apkName)) {
                    zipFile = file;
                }
                Log.d(TAG, "onHandleIntent: file=" + file.getAbsolutePath() + "  length=" + file.length());
            }
//            Log.d(TAG, "onHandleIntent: zipFile="+zipFile.getAbsolutePath()+"  length="+zipFile.length());
//            ToastUtils.showShort("正在解压");
//            List<File> files = ZipUtils.unzipFile(downloadFile,dir);
            NotificationUtils.cancleNotification(0);
//            ToastUtils.showShort(getString(R.string.update_xxz_success));
            EventBus.getDefault().post(new TcpUpdateFeiLong());
//            EventBus.getDefault().post(new PlayTTs(getString(R.string.update_xxz_success)));
//            downloadFile.delete();
            update();
        } catch (Exception e) {
            Log.e(TAG, "download apk file error", e);
        } finally {
            if (out != null) {
                try {
//                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private void updateProgress(int progress) {
        //"正在下载:" + progress + "%"
        mBuilder.setContentText(this.getString(R.string.download_progress, progress)).setProgress(100, progress, false);
        //setContentInent如果不设置在4.0+上没有问题，在4.0以下会报异常
        PendingIntent pendingintent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
        mBuilder.setContentIntent(pendingintent);
        mNotifyManager.notify(0, mBuilder.build());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

//    private void update() {
//        File rootDir = Environment.getExternalStorageDirectory();
//        File homeDir = new File(rootDir, "home");
//        File exagearZipFile = new File(rootDir, "exagear.zip");
//        File sourceZipFile = new File("/storage/emulated/0/exagear.zip");
//        if (!homeDir.exists()) {
//            if (!homeDir.mkdirs()) {
//                System.err.println("无法创建'home'文件夹");
//                return;
//            }
//        }
//        if (!exagearZipFile.exists()) {
//            try (FileInputStream fis = new FileInputStream(sourceZipFile);
//                 FileOutputStream fos = new FileOutputStream(exagearZipFile)) {
//                byte[] buffer = new byte[1024];
//                int length;
//                while ((length = fis.read(buffer)) > 0) {
//                    fos.write(buffer, 0, length);
//                }
//                System.out.println("'exagear.zip'已成功复制到'home'文件夹");
//                Log.d("FileManager", "exagear.zip'已被覆盖在'home'文件夹");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        } else {
//            try (FileInputStream fis = new FileInputStream(sourceZipFile);
//                 FileOutputStream fos = new FileOutputStream(exagearZipFile)) {
//                fis.getChannel().transferTo(0, fis.getChannel().size(), fos.getChannel());
//                Log.d("FileManager", "exagear.zip'已被覆盖在'home'文件夹");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        File file = new File("/storage/emulated/0/home/exagear.zip");
//        if (file.exists()) {
//            Log.d("FileManager", "文件'/storage/emulated/0/home/exagear.zip'存在");
//        } else {
//            Log.d("FileManager", "文件'/storage/emulated/0/home/exagear.zip'不存在");
//        }
//    }

    private void update() {
//        createOrReplaceZipFile();
    }

    private void createOrReplaceZipFile() {
        // 定义路径

        File rootDir = Environment.getExternalStorageDirectory();
        File homeDir = new File(rootDir, "/data/data/0/com.eltechs.ed/files/home");
        File exagearZipFile = new File(homeDir, "exagear.zip");
        File sourceZipFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/exagear.zip");

        // 检查并创建"home"文件夹
        if (!homeDir.exists() && !homeDir.mkdirs()) {
            // 创建文件夹失败的处理
            Log.e("FileManager", "无法创建'home'文件夹");
            return;
        }

        // 检查"home"文件夹中是否存在"exagear.zip"
        if (!exagearZipFile.exists()) {
            // 如果不存在，从源路径复制文件到"home"文件夹
            copyFile(sourceZipFile, exagearZipFile);
        } else {
            // 如果存在，覆盖文件（注意：这会导致原文件内容丢失）
            replaceFile(sourceZipFile, exagearZipFile);
        }
    }

    private void copyFile(File src, File dst) {
        try (FileInputStream fis = new FileInputStream(src);
             FileOutputStream fos = new FileOutputStream(dst)) {

            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
            Log.d("FileManager", "'exagear.zip'已成功复制到'home'文件夹"+src.length()+"-----------"+dst.length());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void replaceFile(File src, File dst) {
        // 如果dst是一个目录，你可能需要重新命名或删除它然后复制新的文件
        // 但在这个例子中，我们假设它是一个文件
        dst.delete(); // 删除旧文件
        copyFile(src, dst); // 复制新文件
        Log.d("FileManager", "'exagear.zip'已被覆盖在'home'文件夹"+src.getAbsolutePath()+"----"+src.length()+"-----------"+dst.getAbsolutePath()+"----"+dst.length());
    }

}
